import logging
import signal
import socket
import time

import epoll_config
import threading

RUNING_TIMES = 1000
THREAD_NUM = 10000


def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(epoll_config.ADDRESS)

    start_time = time.time()
    num = 1
    try:
        while epoll_config.RUNING and (not RUNING_TIMES or num <= RUNING_TIMES):
            # logging.debug(is_server_alived(sock))
            msg = 'Hello World @ %s' % time.strftime('%Y-%m-%d %H:%M:%S')
            try:
                logging.debug('发出：%s', msg)
                start_time_one = time.time()
                sock.sendall(bytes(msg, encoding='utf-8'))
                data = sock.recv(1024)
                logging.debug('收到：%r ... 间隔时间：%.3fms', data, (time.time() - start_time_one) * 1000)
                time.sleep(1)
                # break
            except KeyboardInterrupt:
                logging.info('KeyboardInterrupt')
                epoll_config.RUNING = False
            num += 1
        logging.info('关闭连接...')
        sock.close()
    except Exception as error:
        logging.error(error)
    finally:
        logging.info('退出 ... %d, 耗时：%.3fs', num, time.time() - start_time)


def multiple_threads_test():
    threads = []
    for i in range(1, THREAD_NUM + 1):
        t = threading.Thread(target=main, name='t#%03d' % i)
        t.start()
        threads.append(t)
    for t in threads:
        t.join()


if __name__ == '__main__':
    # main()
    multiple_threads_test()
